package co.legu.carpool.api.wechat.web.common;

import co.legu.carpool.api.route.service.IRouteService;
import co.legu.carpool.api.wechat.util.WechatSession;
import co.legu.modules.auth.annotation.NoNeedAuth;
import co.legu.modules.auth.util.Login;
import co.legu.modules.common.web.util.ServletBox;
import co.legu.modules.sysconfig.util.SysConfig;
import co.legu.modules.wechat.util.Wechat;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Optional;

@RestController
@RequestMapping("/api/wechat")
@Slf4j
@NoNeedAuth
public class CommonWechatController {

    @Autowired
    private IRouteService routeService;

    /**
     * @api {get} /api/wechat/skipLogin 微信 - 跳过登录
     * @apiDescription 测试环境跳过微信登录使用
     * @apiGroup wechat
     * @apiVersion 1.0.0
     * @apiParam {String} openId 微信的openId
     * @apiParam {String} appId 公众号的appId
     * @apiParam {String} code 微信返回的code
     * @apiSuccess {Object} null 空返回值
     */
    @GetMapping("/skipLogin")
    public void skipLogin(String openId,String appId,String code){
        WechatSession.appid(Optional.ofNullable(appId).orElse("wx787faed660ab15a3"));
        WechatSession.code(Optional.ofNullable(code).orElse("061gctos1uvLkk0hiDos1w0tos1gctoB"));
        WechatSession.openid(Optional.ofNullable(openId).orElse("o8mp1szlyHef73NHYktM_FrUIWGY"));
        Login.uid(openId);
    }

    /**
     * 授权登录回调
     */
    @GetMapping("/{appid}/login")
    public void login(@PathVariable String appid, String code, String routeId) throws IOException {
        // 获取用户的 OpenId
        var openId = Wechat.openid(appid, code);
        // 输出调试日志
        log.debug("wechat login -> appid: {}, code: {}, openId: {}", appid, code, openId);
        // 将 OpenId、Appid 存 Session
        WechatSession.appid(appid);
        WechatSession.code(code);
        WechatSession.openid(openId);
        Login.uid(openId);


        // 查询当前路线
        var route = routeService.getById(routeId);
        if (route == null){
//            gotoFailUrl();
            ServletBox.response().sendRedirect("https://carpool.shanch.cn/error");
        }
        // 成功页面
        String successUrl = MessageFormat.format("https://carpool.shanch.cn?routeId={0}&openId={1}", routeId, openId);
        ServletBox.response().sendRedirect(successUrl);
//         gotoSuccessUrl();

    }

    /**
     * 跳任意页
     */
    private void gotoCallbackUrl(@NonNull String callback) throws IOException {
        String url = URLDecoder.decode(callback, StandardCharsets.UTF_8);
        ServletBox.response().sendRedirect(url);
    }

    /**
     * 跳成功页
     */
    private void gotoSuccessUrl() throws IOException {
        String url = "https://carpool.shanch.cn/home";
        ServletBox.response().sendRedirect(url);
    }

    /**
     * 跳失败页
     */
    private void gotoFailUrl() throws IOException {
        String url = Wechat.spliceUrl(WechatSession.appid(), SysConfig.getString("wechat.login.fail.url"));
        ServletBox.response().sendRedirect(url);
    }

    @NoNeedAuth
    @GetMapping(produces = "text/plain;charset=utf-8",path = "/test")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);

        return echostr;
    }

}
